"use strict";

angular.module('app.sensor').controller('DataChartsCtrl', function ($scope, $stateParams, $http, $cookieStore, $location) {
    $scope.deviceid = $location.search().deviceid;
    $scope.userid = $cookieStore.get('userid');
    $scope.fid = $cookieStore.get('userinfo').fid;
    $scope.paginationConf = {
        currentPage: 1,
        itemsPerPage: 10,
        pagesLength: 5,
        totalItems: 20,
        perPageOptions: [10, 20, 30, 40, 50],
        plan: 0,
        onChange: function () {
        }
    };
    //初始化
    $scope.initField = function () {
        $("#barfield").empty();
        $("#piefield").empty();
        $("#linefield").empty();
    }
    $scope.initBtn = function () {
        $(".check").attr("disabled", true);
        $(".plan").attr("disabled", true);
        $(".sureplan").attr("disabled", true);
        $('.check').attr("checked", false);
    }
    $scope.times = [
        { id: 1, name: "一天" },
        { id: 2, name: "一星期" },
        { id: 3, name: "一月" },
        { id: 4, name: "一年" },
        { id: 5, name: "两年" },
        { id: 6, name: "三年" }
    ];
    $scope.charts = [
       { id: "line", name: "折线图" },
       { id: "bar", name: "柱状图" },
       { id: "pie", name: "饼图" }
    ];
    $scope.plans = [
        { id: '1', name: "方案模板一" },
        { id: '2', name: "方案模板二" },
        { id: '3', name: '方案模板三' },
        { id: '4' ,name:"自由组合方案"}
    ];
    $scope.planid = '1';
    //折线图
    var myChart1 = echarts.init(document.getElementById('line'));
    var option1 = {
        title: {
            text: ''
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '邮件营销',
                type: 'line',
                stack: '总量',
                data: [120, 132, 101, 134, 90, 230, 210]
            },
            {
                name: '联盟广告',
                type: 'line',
                stack: '总量',
                data: [220, 182, 191, 234, 290, 330, 310]
            },
            {
                name: '视频广告',
                type: 'line',
                stack: '总量',
                data: [150, 232, 201, 154, 190, 330, 410]
            },
            {
                name: '直接访问',
                type: 'line',
                stack: '总量',
                data: [320, 332, 301, 334, 390, 330, 320]
            },
            {
                name: '搜索引擎',
                type: 'line',
                stack: '总量',
                data: [820, 932, 901, 934, 1290, 1330, 1320]
            }
        ]
    };

    // 1end
    // 柱状图
    var myChart2 = echarts.init(document.getElementById('bar'));
    var option2 = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value'
        },
        yAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        series: [
            {
                name: '直接访问',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: true,
                        position: 'insideRight'
                    }
                },
                data: [320, 302, 301, 334, 390, 330, 320]
            },
            {
                name: '邮件营销',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: true,
                        position: 'insideRight'
                    }
                },
                data: [120, 132, 101, 134, 90, 230, 210]
            },
            {
                name: '联盟广告',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: true,
                        position: 'insideRight'
                    }
                },
                data: [220, 182, 191, 234, 290, 330, 310]
            },
            {
                name: '视频广告',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: true,
                        position: 'insideRight'
                    }
                },
                data: [150, 212, 201, 154, 190, 330, 410]
            },
            {
                name: '搜索引擎',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: true,
                        position: 'insideRight'
                    }
                },
                data: [820, 832, 901, 934, 1290, 1330, 1320]
            }
        ]
    };
    //2end
    //饼图
    var myChart3 = echarts.init(document.getElementById('pie'));
    var option3 = {
        title: {
            text: '',
            subtext: '',
            x: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
        },
        series: [
            {
                name: '访问来源',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [
                    { value: 335, name: '直接访问' },
                    { value: 310, name: '邮件营销' },
                    { value: 234, name: '联盟广告' },
                    { value: 135, name: '视频广告' },
                    { value: 1548, name: '搜索引擎' }
                ],
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    //3end
    $scope.selectPlan = function (id) {
        console.log(id);
        if (id == "1") {
            myChart1.setOption(option1);
            myChart2.setOption(option2);
            myChart3.clear();
            $scope.initField();
            $scope.initBtn();
            $("#linefield").append(content);
            $("#barfield").append(content);
            $("#planName").css("display", "block");
        } else if (id == "2") {
            myChart1.setOption(option1);
            myChart3.setOption(option3);
            myChart2.clear();
            $scope.initField();
            $scope.initBtn();
            $("#linefield").append(content);
            $("#piefield").append(content);
            $("#planName").css("display", "block");
        } else if (id == "3") {
            myChart2.setOption(option2);
            myChart3.setOption(option3);
            myChart1.clear();
            $scope.initField();
            $scope.initBtn();
            $("#piefield").append(content);
            $("#barfield").append(content);
            $("#planName").css("display", "block");
        } else if (id == "4") {
            myChart1.clear();
            myChart2.clear();
            myChart3.clear();
            $scope.initField();
            $scope.chartCheck = false;
            $(".check").attr("disabled", false);
            $(".plan").attr("disabled", false);
            $(".sureplan").attr("disabled", true);
        }
    };
    var content = null;
    $http.get(baseurl + "/protocol_field_get").then(function (res) {
        $scope.fields = res.data.info;
        var content1 = ' <select class="form-control select"> ' +
                '  <option value="' + $scope.fields[0].id + '" selected>' + $scope.fields[0].name + '</option> ' +
                 '  <option value="' + $scope.fields[1].id + '">' + $scope.fields[1].name + '</option> ' +
                 '</select>';
        content = content1;
        $scope.selectPlan($scope.planid);
    });
    $scope.sends = function () {
        $scope.page_obj = {
            page: $scope.paginationConf.currentPage,
            rows: $scope.paginationConf.itemsPerPage
        };
        // 获得图表数据
        $http.post(baseurl + '/list/select/charts', $scope.page_obj).then(function (res) {
            console.log(res.data.rows);
            if (res.data.ret == 1 && res.data.rows.length > 0) {
                $scope.types = res.data.rows;
                $scope.paginationConf.totalItems = res.data.records;
            }
        });
    };
    // 图表
    $scope.Edit_pro = function (obj) {
        $scope.editobj = obj;
        console.log($scope.editobj);
    };
    // 编辑图表
    $scope.sure_edit = function () {
        console.log($scope.editobj);
        //delete $scope.editobj.type_field;
        //$scope.editobj.type_filed = '';
        //$scope.editobj.type_filed = JSON.parse($scope.editobj.type_field);
        //scope.editobj.type_field = {};
       
        $scope.editobj.type_field = JSON.parse($scope.editobj.type_field);
        $scope.editobj.type_field[$scope.editobj.type] = $scope.editobj.field;
        $scope.editobj.type_field = JSON.stringify($scope.editobj.type_field);
       
        return;
        $http.put(baseurl + '/data/charts?id==' + $scope.editobj.id, $scope.editobj).then(function (res) {
            if (res.data.ret == 1) {
                $scope.editobj = {};
                $("#editAlert").modal('hide');
                new Notify('success', '修改成功');
                $scope.sends();
            }
        })
    };
    // 删除这条预算成本数据
    $scope.showDelDialog = function (id) {
        $scope.dele_id = id;
    };
    $scope.sure_del = function () {
        $http.delete(baseurl + '/data/charts?id==' + $scope.dele_id).then(function (res) {
            if (res.data.ret == 1) {
                $("#delAlert").modal('hide');
                new Notify('success', '删除成功');
                $scope.sends();
            }
        })
    };
    $scope.jump_chart = function () {
        window.location.href = '#/watchcharts';
    }
    $scope.$watch('paginationConf.currentPage + paginationConf.itemsPerPage', $scope.sends);
    var lineValue;
    var barValue;
    var pieValue;
    
    //生成图表
    $scope.play_plan = function () {
        if ($scope.chartCheck == '' || $scope.chartCheck == null) {
            new Notify('info', '图表类型不能为空');
            return;
        } else if ($scope.chartCheck) {
            console.log($scope.chartCheck);
            if (!$scope.chartCheck.line) {
                delete $scope.chartCheck['line'];
            };
            console.log($scope.chartCheck);
            if (!$scope.chartCheck.bar) {
                delete $scope.chartCheck['bar'];
            };
            console.log($scope.chartCheck);
            if (!$scope.chartCheck.pie) {
                delete $scope.chartCheck['pie'];
            };
            console.log($scope.chartCheck);
            if ($scope.chartCheck.line && $scope.chartCheck.bar && $scope.chartCheck.pie) {
                alert("line,bar,pie");
                $scope.initField();
                clear();
                myChart1.setOption(option1);
                myChart2.setOption(option2);
                myChart3.setOption(option3);
                $("#linefield").append(content);
                $("#barfield").append(content);
                $("#piefield").append(content);
                $("#planName").css("display", "block");
                $(".sureplan").attr("disabled", false);
            } else if ($scope.chartCheck.line && $scope.chartCheck.bar) {
                alert("line,bar");
                clear();
                $scope.initField();
                myChart1.setOption(option1);
                myChart2.setOption(option2);
                $("#linefield").append(content);
                $("#barfield").append(content);
                $("#planName").css("display", "block");
                $(".sureplan").attr("disabled", false);
            } else if ($scope.chartCheck.bar && $scope.chartCheck.pie) {
                alert("bar,pie");
                clear();
                $scope.initField();
                myChart2.setOption(option2);
                myChart3.setOption(option3);
                $("#barfield").append(content);
                $("#piefield").append(content);
                $("#planName").css("display", "block");
                $(".sureplan").attr("disabled", false);
            } else if ($scope.chartCheck.line && $scope.chartCheck.pie) {
                alert("line,pie");
                clear();
                $scope.initField();
                myChart1.setOption(option1);
                myChart3.setOption(option3);
                $("#linefield").append(content);
                $("#piefield").append(content);
                $("#planName").css("display", "block");
                $(".sureplan").attr("disabled", false);
            }else if ($scope.chartCheck.line) {
                alert("line");
                clear();
                $scope.initField();
                myChart1.setOption(option1);
                $("#linefield").append(content);
                $("#planName").css("display", "block");
                $(".sureplan").attr("disabled", false);
            } else if ($scope.chartCheck.bar) {
                alert("bar");
                clear();
                $scope.initField();
                myChart2.setOption(option2);
                $("#barfield").append(content);
                $("#planName").css("display", "block");
                $(".sureplan").attr("disabled", false);
            } else if ($scope.chartCheck.pie) {
                alert("pie");
                clear();
                $scope.initField();
                myChart3.setOption(option3);
                $("#piefield").append(content);
                $("#planName").css("display", "block");
                $(".sureplan").attr("disabled", false);
            } else {
                clear();
                $scope.initField();
                alert("else if");
                $(".sureplan").attr("disabled", true);
                console.log($scope.chartCheck);
                if (!$scope.chartCheck.pie) {
                    delete $scope.chartCheck['pie'];
                };
                if (!$scope.chartCheck.line) {
                    delete $scope.chartCheck['line'];
                };
                if (!$scope.chartCheck.bar) {
                    delete $scope.chartCheck['bar'];
                }
                console.log($scope.chartCheck);
            }
        } else {
            alert("直接else");
            clear();
            $scope.initField();
            console.log($scope.chartCheck);
            $(".sureplan").attr("disabled", true);
            if (!$scope.chartCheck.pie) {
                delete $scope.chartCheck['pie'];
            };
            if (!$scope.chartCheck.line) {
                delete $scope.chartCheck['line'];
            };
            if (!$scope.chartCheck.bar) {
                delete $scope.chartCheck['bar'];
            }
            console.log($scope.chartCheck);
        }
    };
    //清除图表
    function clear() {
        if (myChart1 != null) {
            myChart1.clear();
        }
        if (myChart2 != null) {
            myChart2.clear();
        }
        if (myChart3 != null) {
            myChart3.clear();
        }
    }
    //保存方案到数据库
    $scope.addobj = {};
    $scope.surePlan = function (id) {
        $scope.sumobj = {};
        barValue = $("#barfield>.select option:selected").val();
        pieValue = $("#piefield>.select option:selected").val();
        lineValue = $("#linefield>.select option:selected").val();
        $scope.sumobj.field = "";
        $scope.sumobj.type = "";
        $scope.sumobj.name = $scope.addobj.name;

        console.log($scope.chartCheck);
        if ($scope.addobj.name == '' || $scope.addobj.name == null || $scope.addobj.name == undefined) {
            new Notify('info', '方案名称不能为空');
            return;
        }
        if (lineValue != '' && lineValue != null && lineValue != undefined) {
            if ($scope.sumobj.field == '') {
                $scope.sumobj.field += lineValue;
            } else {
                $scope.sumobj.field += "," + lineValue;
            }
        } else {
            $scope.sumobj.field += '';
        }
        if (barValue != '' && barValue != null && barValue != undefined) {
            if ($scope.sumobj.field == '') {
                $scope.sumobj.field += barValue;
            } else {
                $scope.sumobj.field += "," + barValue;
            }            
        } else {
            $scope.sumobj.field += '';
        }
        if (pieValue != '' && pieValue != null && pieValue != undefined) {
            if ($scope.sumobj.field == '') {
                $scope.sumobj.field += pieValue;
            } else {
                $scope.sumobj.field += "," + pieValue;
            }
           
        } else {
            $scope.sumobj.field += '';
        }
        //获取key值
        $scope.key = Object.keys($scope.chartCheck);
        var key = $scope.key.join(',');
        $scope.sumobj.type += key;
        //把字段和类型存在type_field以json形式
        $scope.sumobj.type_field = {};
        if (lineValue != undefined && lineValue != '' && lineValue != null) {
            $scope.sumobj.type_field.line = lineValue;
        }
        if (barValue != undefined && barValue != '' && barValue != null) {
            $scope.sumobj.type_field.bar = barValue;
        }
        if (pieValue != undefined && pieValue != '' && pieValue != null) {
            $scope.sumobj.type_field.pie = pieValue;
        }
        $scope.sumobj.type_field = JSON.stringify($scope.sumobj.type_field);
        $http.post(baseurl + "data/charts", $scope.sumobj).then(function (res) {
            console.log(res.data);
            $scope.sends();
            clear();
            $scope.initField();
            $("#planName").css("display", "none");
        })
    };
})